package com.djx.CRUD;

import com.djx.utils.MongoDBUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class Update {

    MongoDBUtil util = MongoDBUtil.getInstance();
    MongoDatabase database = util.getDatabase("d01");
    MongoCollection<Document> collection = database.getCollection("c1");

    /**
     * 更新单条数据
     */
    @Test
    public void UpdateOne() {
        //筛选条件
        BasicDBObject map = new BasicDBObject();
        map.put("name", "敦佳星");

        //修改对象
        Document documentz = new Document();
        Document document = new Document();
        document.put("name", "敦佳星");
        document.put("age", 20);
        document.put("sex", "男");
        document.put("school", "石家庄理工职业学院");
        document.put("love", "学习");

        documentz.append("$set", document);

        collection.updateOne(map, documentz);
        System.out.println("修改成功,");
        util.closeDB();
    }


    /**
     * 更新多条数据
     */
    @Test
    public void UpdateMany() {
        //筛选条件
        BasicDBObject map = new BasicDBObject();
        map.put("name", "敦佳星");

        //修改对象
        Document documentz = new Document();
        Document document = new Document();
        document.put("name", "敦佳星");
        document.put("age", 20);
        document.put("sex", "男");
        document.put("school", "石家庄理工职业学院");
        document.put("love", "学习");

        documentz.append("$set", document);

        collection.updateMany(map, documentz);
        System.out.println("修改成功,");
        util.closeDB();
    }

    /**
     * Filter 筛选条件
     */
    @Test
    public void Filter() {
        //筛选条件
        List<Bson> list = new ArrayList<>();
        list.add(Filters.eq("name", "敦佳星"));
        list.add(Filters.eq("sex", "男"));
        //筛选条件对象
        Bson and = Filters.and(list);

        //修改对象
        Document document = new Document();
        document.put("name", "敦佳星");
        document.put("age", 20);
        document.put("sex", "男");
        document.put("school", "石家庄理工职业学院");
        document.put("like", "学习,JAVA");
        document.put("love", "goodGirls");
        Document doc = new Document();
        doc.append("$set", document);

//        collection.updateMany(and, doc);
        collection.updateOne(and, doc);
        System.out.println("修改成功,");
        util.closeDB();


    }
}
